<template>
  <a-modal title="新建数据源"
           v-model:open="open"
           @ok="onSubmit"
           :confirm-loading="loading">
    <a-form :label-col="{span:5}"
            :wrapper-col={span:17} ref="formRef" :model="form">
      <a-form-item label="名称" name="name"
                   :rules="{required:true,message:'名称不能为空',trigger:'blur'}">
        <a-input :maxlength="8" v-model:value="form.name"
                 placeholder="请输入名称，8个中文字符以内" show-count allow-clear/>
      </a-form-item>
      <a-form-item label="状态样式">
        <use-color v-model:value="form.color"/>
      </a-form-item>
      <a-form-item label="排序" help="数字越小越靠前" class="margin-none">
        <a-input-number v-model:value="form.sort" :min="0" :max="999" :step="1"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">
import {reactive, ref, watch} from "vue";
import UseColor from "@/components/UseColor.vue";
import {useRoute} from 'vue-router'
import {createDictionaryData, updateDictionaryData} from '@/api/modules/dictionary'
import useMessage from "@/plugin/useMessage";


const route = useRoute()
const emits = defineEmits(['change'])
const open = defineModel('visible',{default:false,type:Boolean})
const props = defineProps({
  data :{type:Object as DictionaryData,default:{}},
})
const loading = ref<boolean>(false)
const form = reactive<DictionaryData>({
  id:0,
  name:'',
  color:'',
  dictionary_id: route.query.id,
  sort:0
})
const formRef = ref()
/**
 * 提交数据源表单
 * 根据form.id判断是否为更新状态
 */
const onSubmit = () => {
  formRef.value.validate().then(async () => {
    loading.value = true
    let res: HttpResponse,model:ActionType= 'create'
    if (form.id) {
      model = 'update'
      res = await updateDictionaryData(form.id, form)
    } else {
      delete form.id
      res = await createDictionaryData(form)
    }
    if (res.code === 200 && res.data) {
      emits('change',{model:model,data:res.data})
      loading.value = false
      open.value = false
    }
    useMessage(res.code, res.message)
  }).catch((e) => {
    console.log(e);
  }).finally(() => {
    loading.value = false
  })
}
watch(()=>props.data,(item:DictionaryData)=>{
  if (item.id) {
    form.id = props.data.id
    form.name = props.data.name
    form.color = props.data.color
    form.sort = props.data.sort
  }
})
</script>

<style scoped>

</style>